package fl.ass.service.api;

import java.util.ArrayList;
import java.util.List;

import cmm.comm.facade.framework.api.ISysRegionApiService;
import cmm.comm.facade.framework.condition.SysRegionQueryCondition;
import cmm.comm.facade.framework.dto.SysRegionDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import fl.ass.facade.api.IAssParkingApi;
import fl.ass.facade.condition.AssParkingMgQueryCondition;
import fl.ass.facade.condition.AssParkingQueryCondition;
import fl.ass.facade.condition.AssParkingValidQueryCondition;
import fl.ass.facade.dto.AssParkingDTO;
import fl.ass.facade.dto.AssParkingMgDTO;
import fl.ass.facade.dto.AssParkingValidDTO;
import fl.ass.facade.dto.MessageDTO;
import fl.ass.service.service.IAssParkingMgService;
import fl.ass.service.service.IAssParkingService;
import fl.ass.service.service.IAssParkingValidService;

@Service
public class AssParkingApi implements IAssParkingApi {
	
	private static final Logger logger = LoggerFactory.getLogger(AssParkingApi.class);
	
	/**
	 * 停车场服务
	 */
	@Autowired
	private IAssParkingService assParkingService;
	
	/**
	 * 资产管理员服务
	 */
	@Autowired
	private IAssParkingMgService assParkingMgService;
	
	/**
	 * 停车场有效期服务
	 */
	@Autowired
	private IAssParkingValidService assParkingValidService;
	
	@Autowired
	private ISysUsrApiService sysUsrApiService;//系统用户API 暴露服务

    @Autowired
    private ISysRegionApiService sysRegionApiService;

	@Override
	public MessageDTO<String> saveAssParking(AssParkingDTO dto) {
		MessageDTO<String> response = new MessageDTO<String>();
		try {
            /*
              获取省信息开始
             */
            SysRegionQueryCondition qc = new SysRegionQueryCondition();
            qc.setRgnLvl(1);
            qc.setRgnCd(dto.getProvinceCd());
            List<SysRegionDTO> sysRegionProvince = this.sysRegionApiService.searchRegionList(qc);
            if (CollectionUtils.isNotEmpty(sysRegionProvince)) {
                dto.setProvinceCode(sysRegionProvince.get(0).getShtNm());
            }
            /*
              获取省信息结束
             */
			Long id = assParkingService.add(dto);
			response.setId(id);//返回ID值
			response.setSuccess(true);
		} catch (Exception e) {
			response.setMessage(e.getMessage());
		}
		return response;
	}

	@Override
	public MessageDTO<String> updateAssParking(AssParkingDTO dto) {
		MessageDTO<String> response = new MessageDTO<String>();
		try {
			assParkingService.modify(dto);
			response.setSuccess(true);
		} catch (Exception e) {
			response.setMessage(e.getMessage());
		}
		return response;
	}

	@Override
	public MessageDTO<String> removeAssParking(Long id) {
		MessageDTO<String> response = new MessageDTO<String>();
		try {
			assParkingService.removeById(id);
			response.setSuccess(true);
		} catch (Exception e) {
			response.setMessage(e.getMessage());
		}
		return response;
	}

	@Override
	public Pager findAssParkingsByPager(Pager page) {
		//用户模块相关表优化-JL-20181106
		page = this.assParkingService.searchListPage(page);
		List<AssParkingDTO> list = (List<AssParkingDTO>)page.getResultList();
		//遍历列表结果
		if(CollectionUtils.isNotEmpty(list) && list.size()>0){

			for(AssParkingDTO dto : list){
			    /*
                  获取省市信息开始
                 */
                SysRegionQueryCondition qc = new SysRegionQueryCondition();
                qc.setRgnLvl(1);
                qc.setRgnCd(dto.getProvinceCd());
                List<SysRegionDTO> sysRegionProvince = this.sysRegionApiService.searchRegionList(qc);
                if (CollectionUtils.isNotEmpty(sysRegionProvince)) {
                    dto.setProvinceCd(sysRegionProvince.get(0).getRgnNm());
                }
                qc.setRgnLvl(2);
                qc.setRgnCd(dto.getCityCd());
                List<SysRegionDTO> sysRegionCity = this.sysRegionApiService.searchRegionList(qc);
                if (CollectionUtils.isNotEmpty(sysRegionCity)) {
                    dto.setCityCd(sysRegionCity.get(0).getRgnNm());
                }
                /*
                  获取省市信息结束
                 */

				//1.根据停车场ID查询相应资管员列表
				AssParkingMgQueryCondition mgQc = new AssParkingMgQueryCondition();
				mgQc.setParkId(dto.getId());
				mgQc.setIsDel(0);
				List<AssParkingMgDTO> mgList = this.assParkingMgService.searchList(mgQc);
				List<Long> usrIds = new ArrayList<Long>();
				for(AssParkingMgDTO mg : mgList){
					usrIds.add(mg.getManagerId());
				}
				//2.根据资管员ID查询资管员名称，并拼接“史勇[1000945],于瑞超[1000897]”这种形式
				String assManagers = "";
				if(CollectionUtils.isNotEmpty(usrIds)){
					SysUsrQueryCondition usQc = new SysUsrQueryCondition();
					usQc.setSysCd("11000");
					usQc.setUsrIds(usrIds);
					List<SysUsrDTO> usrList = this.sysUsrApiService.searchSysUsrList(usQc);
					int i=0;
					for(SysUsrDTO usr : usrList){
						i++;
						assManagers = assManagers.concat(usr.getRefRlNm()+"["+usr.getUsrNm()+"]");
						if(i < usrList.size()){
							assManagers = assManagers.concat(",");
						}
					}
				}
				dto.setAssManagers(assManagers);
			}
		}
		return page;
	}

	@Override
	public List<AssParkingDTO> findAssParkings(AssParkingQueryCondition condition) {
        List<AssParkingDTO> assParkingDTOS = assParkingService.searchList(condition);
        for (AssParkingDTO dto : assParkingDTOS) {
            /*
              获取省市信息开始
             */
            SysRegionQueryCondition qc = new SysRegionQueryCondition();
            qc.setRgnLvl(1);
            qc.setRgnCd(dto.getProvinceCd());
            List<SysRegionDTO> sysRegionProvince = this.sysRegionApiService.searchRegionList(qc);
            if (CollectionUtils.isNotEmpty(sysRegionProvince)) {
                dto.setProvinceCd(sysRegionProvince.get(0).getRgnNm());
            }
            qc.setRgnLvl(2);
            qc.setRgnCd(dto.getCityCd());
            List<SysRegionDTO> sysRegionCity = this.sysRegionApiService.searchRegionList(qc);
            if (CollectionUtils.isNotEmpty(sysRegionCity)) {
                dto.setCityCd(sysRegionCity.get(0).getRgnNm());
            }
            /*
              获取省市信息结束
             */
        }
        return assParkingDTOS;
	}

	/* (non-Javadoc)
	 * @see fl.ass.facade.api.IAssParkingApi#saveAssParkingValid(fl.ass.facade.dto.AssParkingValidDTO)
	 */
	/*@Override
	public MessageDTO<String> saveAssParkingValid(AssParkingValidDTO dto) {
		MessageDTO<String> response = new MessageDTO<String>();
		try {
			response = assParkingService.saveAssParkingValid(dto);
			response.setSuccess(true);
		} catch (Exception e) {
			response.setMessage(e.getMessage());
		}
		return response;
	}*/
	@Override
	public MessageDTO<String> saveAssParkingValid(AssParkingValidDTO dto) {
		MessageDTO<String> response = new MessageDTO<String>();
		try {
			Long id = assParkingValidService.add(dto);
			response.setId(id);//返回ID值
			response.setSuccess(true);
		} catch (Exception e) {
			response.setMessage(e.getMessage());
		}
		return response;
	}
	
	/**
	 * 保存停车场资产管理员信息
	 * @author JiLi
	 * @param dto
	 * @return
	 */
	@Override
	public MessageDTO<String> saveAssParkingMg(AssParkingMgDTO dto){
		MessageDTO<String> response = new MessageDTO<String>();
		try {
			Long id = assParkingMgService.add(dto);
			response.setId(id);//返回ID值
			response.setSuccess(true);
		} catch (Exception e) {
			response.setMessage(e.getMessage());
		}
		return response;
	}
	
	/**
	 * 根据主键查询停车场基本信息
	 * @author JiLi
	 * @param id
	 * @return
	 * @throws BaseException
	 */
	@Override
	public AssParkingDTO selectAssParkingById(Long id) throws BaseException {
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.newLogger("根据主键查询停车场信息失败,主键参数为空").info();
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return assParkingService.selectById(id);
	}
	
	/**
     * 不分页查询资产管理员
     * @author JiLi
     * @param condition
     * @return
     */
	@Override
	public List<AssParkingMgDTO> searchAssMgsList(AssParkingMgQueryCondition condition) throws BaseException {
		if(null == condition){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"查询对象不能为空!");
		}
		return this.assParkingMgService.searchList(condition);
	}
	
	/**
	 * 删除资产管理员信息
	 * @author JiLi
	 * @param
	 * @return
	 * @throws BaseException
	 */
	@Override
	public boolean removeAssParkMgById(Long id) throws BaseException {
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.newLogger("删除资产管理员失败,主键参数为空").info();
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "主键不能为空!");
		}
		return this.assParkingMgService.removeById(id);
	}
	
	/**
	 * 导出停车场信息
	 * @param condition
	 * @param orgCd
	 * @return
	 * @throws BaseException
	 */
	@Override
	public String exportAssParking(AssParkingQueryCondition condition, String orgCd) throws BaseException {
		if(StringUtils.isEmpty(orgCd)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "组织架构代码不能为空.");
		}
		if(null==condition){
			//throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "查询条件不能为空.");
		}
		return this.assParkingService.exportAssParking(condition, orgCd);
	}
	
	/**
	 * 修改停车场有效期信息
	 * @param dto
	 * @return
	 */
	@Override
	public MessageDTO<String> updateAssParkingValid(AssParkingValidDTO dto) {
		MessageDTO<String> response = new MessageDTO<String>();
		try {
			assParkingValidService.modify(dto);
			response.setSuccess(true);
		} catch (Exception e) {
			response.setMessage(e.getMessage());
		}
		return response;
	}
	
	/**
	 * 根据城市代码获取停车场名称数据
	 * @param rgnCd
	 * @param sysCd 系统代码
	 * @return
	 * @throws BaseException
	 */
	@Override
	public List<AssParkingDTO> getParkNmByRgnCd(String provinceCd, String cityCd, String parkId) throws BaseException {
		//判断参数是否为空
		if(StringUtils.isEmpty(provinceCd) || StringUtils.isEmpty(cityCd)){
			BaseLogUtils.newLogger("根据区域代码查询区域对象失败,区域代码参数为空").info();
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "区域代码参数不能为空!");
		}
		return this.assParkingService.searchParkNmByRgnCd(provinceCd, cityCd, parkId);
	}
	
	/**
     * 不分页查询停车场有效期
     * @author JiLi
     * @param condition
     * @return
     */
	@Override
	public List<AssParkingValidDTO> searchValidList(AssParkingValidQueryCondition condition) throws BaseException {
		if(null == condition){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"查询对象不能为空!");
		}
		return this.assParkingValidService.searchList(condition);
	}
	
	/**
	 * 根据ID获取停车场有效期信息
	 * @param id
	 * @return
	 */
	@Override
	public MessageDTO<AssParkingValidDTO> selectValidInfoById(Long id) {
		MessageDTO<AssParkingValidDTO> response = new MessageDTO<AssParkingValidDTO>();
		if(null == id){
			response.setMessage("parameter：validId is can not be null");
		}
		try {
			AssParkingValidDTO dto = assParkingValidService.selectById(id);
			if(null != dto){
				response.setData(dto);
			}
			response.setSuccess(true);
		} catch (Exception e) {
            BaseLogUtils.newLogger("异常!" + e.getMessage()).setThrowable(e).info();
			response.setMessage(e.getMessage());
		}
		return response;
	}
	
	/**
     * 不分页查询资产管理员
     * @return
     */
	@Override
	public List<AssParkingMgDTO> selectManagerList() throws BaseException {
		return this.assParkingMgService.selectManagerList();
	}
}
